<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexShopCateRequest;
use App\Http\Requests\StoreShopCateRequest;
use App\Http\Requests\UpdateShopCateRequest;
use App\Http\Resources\ShopCateResource;
use App\Models\ShopCate;

class ShopCateController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexShopCateRequest $request)
    {
        $this->authorize('viewAny', ShopCate::class);
        $shopcate = ShopCate::query();

        if ($request->filled('name')) {
            $name = $request->query('name');
            $shopcate->where('name', 'like', '%' . $name . '%');
        }

        $data = $shopcate->with('statuslabel')->orderBy('order', 'ASC')->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response =  ShopCateResource::collection($data);
        $total = $response->total();
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreShopCateRequest $request, ShopCate $shopCate)
    {
        $this->authorize('create', $shopCate);
        $shopCate->fill($request->input());
        $shopCate->save();
        return $this->success('新增商品分类成功', $shopCate);
    }

    /**
     * Display the specified resource.
     */
    public function show(ShopCate $shopCate, $id)
    {
        $data = $shopCate->findOrFail($id);
        $this->authorize('viewAny', $shopCate);
        return $this->success('查询成功', $data->load('statuslabel'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ShopCate $shopCate)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateShopCateRequest $request, ShopCate $shopCate, $id)
    {
        $shopCate = $shopCate->findOrFail($id);
        $this->authorize('update', $shopCate);
        $shopCate->fill($request->input());
        $shopCate->save();
        return $this->success('更新商品分类成功', $shopCate);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(ShopCate $shopCate, $id)
    {
        $shopCate = $shopCate->findOrFail($id);
        $this->authorize('delete', $shopCate);
        $shopCate->delete();
        return $this->success('删除商品分类成功', $shopCate);
    }
}
